package com.hsc.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsc.commonutils.JwtUtils;
import com.hsc.commonutils.R;
import com.hsc.eduservice.client.CommentClient;
import com.hsc.eduservice.entity.EduComment;
import com.hsc.eduservice.entity.vo.UcenterMemberVo;
import com.hsc.eduservice.service.EduCommentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-10-18
 */
@RestController
@RequestMapping("/eduservice/comment")
//@CrossOrigin //gateway解决了可以注掉
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;
    @Autowired
    private CommentClient commentClient;

    /**
     * 根据课程id查询评论列表
     * @param page 哪一页
     * @param limit 每页数量
     * @param courseId 课程id
     * @return
     */
    @ApiOperation(value = "评论分页列表")
    @GetMapping("{page}/{limit}")
    public R index(@ApiParam(name = "page", value = "当前页码", required = true)
                       @PathVariable Long page,
                   @ApiParam(name = "limit", value = "每页记录数", required = true)
                   @PathVariable Long limit,
                   @ApiParam(name = "courseQuery", value = "查询对象", required = false)
                               String courseId){
        Page<EduComment> pageComment = new Page<>(page,limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        commentService.page(pageComment,wrapper);
        List<EduComment> commentList = pageComment.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageComment.getCurrent());
        map.put("pages", pageComment.getPages());
        map.put("size", pageComment.getSize());
        map.put("total", pageComment.getTotal());
        map.put("hasNext", pageComment.hasNext());
        map.put("hasPrevious", pageComment.hasPrevious());
        return R.ok().data(map);
    }

    /**
     * 插入评论
     * @param comment 评论内容
     * @param request 域对象，自动封装
     * @return
     */
    @ApiOperation(value = "添加评论")
    @PostMapping("auth/save")
    public R save(@RequestBody EduComment comment, HttpServletRequest request){
        String id = JwtUtils.getMemberIdByJwtToken(request);
        UcenterMemberVo userInfo = commentClient.getInfo(id);
        comment.setMemberId(userInfo.getId());
        comment.setAvatar(userInfo.getAvatar());
        comment.setNickname(userInfo.getNickname());
        commentService.save(comment);
        return R.ok();
    }



}

